//
//  CarLineView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/2.
//

import UIKit
import WebKit

class CarLineView: UIView {
    var webView: WKWebView!
    var urlStr: String = ""
    var localHtmlStr: String = ""
    var bodyColorHex: String = "#F2F7FA"
    var progressView: UIProgressView! = {
        let tempProgressView = UIProgressView.init(frame: CGRect.init(x: 0, y: NavBarHight-2, width: kScreenWidth, height: 2))
        tempProgressView.backgroundColor = UIColor.white
        tempProgressView.progressTintColor = UIColor.blue
        return tempProgressView
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let configuretion = WKWebViewConfiguration.init()
        configuretion.preferences = WKPreferences()
        configuretion.preferences.minimumFontSize = 0
        configuretion.preferences.javaScriptEnabled = true
        configuretion.preferences.javaScriptCanOpenWindowsAutomatically = true
        configuretion.userContentController = WKUserContentController()
        
        webView = WKWebView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: frame.size.height), configuration: configuretion)
        webView.navigationDelegate = self
        //webView.uiDelegate = self
        webView.backgroundColor = UIColor.init(hex: 0xF2F7FA)
        if #available(iOS 11.0, *) {
            webView.scrollView.contentInsetAdjustmentBehavior = .never
        }
        webView.scrollView.showsHorizontalScrollIndicator = false
        self.addSubview(webView)
        
        //self.loadHtml()
    }
    
    func loadHtml(h5Str: String){
        if h5Str == "" {
            return
        }
        if self.localHtmlStr != "" {
            //说明加载过了
            return
        }
        self.localHtmlStr = h5Str
        let formatWeb = """
                <!DOCTYPEhtml>
                    <html>
                    <head>
                        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"name="viewport">
                        <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
                    </head>
                    <style type="text/css">
                        img{
                            display:inline-block;
                            max-width:100%@;
                        }
                    </style>
                    <body style="background-color: %@">
                        %@
                    </body>
                    </html>
                """
        let tempStr = String(format: formatWeb,
                             "%",
                             bodyColorHex,
                             self.localHtmlStr)
        self.webView.scrollView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        self.webView.loadHTMLString(tempStr, baseURL: nil)
    }
    
    ///监听进度条
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progressView.progress = Float(self.webView.estimatedProgress)
        }
        if self.webView.estimatedProgress == 1 {
            self.webView.isHidden = true
        }else{
            self.webView.isHidden = false
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CarLineView: WKScriptMessageHandler, WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //ios9 延时一点才会有效
    }
    
    ///js调用ios方法
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.name)
        let msgBody = message.body as? String
        switch message.name {
            case "isApp":
                webView.evaluateJavaScript("isAppBack(1)") { (item, error)  in
                }
                
            default:
                ()
        }
    }
    
    ///服务器开始请求的时候调用 过滤域名
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    ///开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
}
